package com.bootdo.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.SysDictDO;
import com.bootdo.common.service.SysDictService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.system.domain.Audit;
import com.bootdo.system.domain.Customer;
import com.bootdo.system.domain.CustomerQrCode;
import com.bootdo.system.domain.SysUserDO;
import com.bootdo.system.domain.VeriCode;
import com.bootdo.system.service.AuditService;
import com.bootdo.system.service.CustomerQrCodeService;
import com.bootdo.system.service.CustomerService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.VeriCodeService;
import com.bootdo.system.util.QRCodeUtil;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RequestMapping("/sys/customer")
@Controller
@Api(value = "/sys/customer", description = "商户操作接口")
public class CustomerController  extends BaseController {
	@Autowired
	CustomerService service;
	
	@Autowired
	UserService userService;
	
	
	@Autowired
	VeriCodeService veriCodeService;
	
	@Autowired
	SysDictService sysDictService;
	
	@Autowired
	AuditService auditService;

	@Autowired
	CustomerQrCodeService customerQrCodeService;


	@ApiOperation(value="商户查询", notes="根据条件查询商户", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "商户id", required = false, paramType="query",dataType = "Long"),
        @ApiImplicitParam(name = "linkerName", value = "联系人姓名", required = false,paramType="query", dataType = "String"),
        @ApiImplicitParam(name = "linkerPhone", value = "联系人电话", required = false,paramType="query", dataType = "String"),
        @ApiImplicitParam(name = "bdId", value = "BD的id", required = false,paramType="query", dataType = "Long"),
        @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, paramType="query",dataType = "Integer"),
        @ApiImplicitParam(name = "pageNum", value = "当前页数", required = true, paramType="query",dataType = "Integer")
	})
	@GetMapping("/list")
	@ResponseBody
	R list(@RequestParam Map<String, Object> param) {
		try {
			Query query = new Query(param);
			List<Customer> customers = service.list(query);
			for(Customer c:customers) {
				SysUserDO u = userService.get(c.getBdId());
				if(u != null)
					c.setBdName(u.getName());
			}
			PageInfo<Customer> pageInfo = new PageInfo<Customer>(customers);
			int total = (int)pageInfo.getTotal();
			PageUtils pageUtil = new PageUtils(customers, total);
			return new R("list",pageUtil);
		}catch(Exception e) {
			e.printStackTrace();
			return R.error();
		}
	}


	@ApiOperation(value="商户详情", notes="根据条件查询商户", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "商户id", required = true,paramType="query", dataType = "Long")
	})
	@GetMapping("/edit")
	@ResponseBody
	R edit( Long id) {
		try {
			Customer c = service.get(id);
			SysUserDO u = userService.get(c.getBdId());
			if(u != null)
				c.setBdName(u.getName());
			return new R("obj",c);
		}catch(Exception e) {
			e.printStackTrace();
			return R.error();
		}
	}

	@ApiOperation(value="商户保存", notes="保存商户", response=String.class)
	@PostMapping("/save")
	@ResponseBody
	R save(@RequestBody Customer customer) {
		try {
			if(checkLinkerPhone(-1L,customer.getLinkerPhone())) {
				return R.error(1, "联系电话已经存在");
			}
			if(customer.getCurrentStep()>7) {
				customer.setStatus(1L);
			}else {
				customer.setStatus(0L);
			}
			if(customer.getCustomerTypeId()>0) {
				SysDictDO dict = sysDictService.get((long)customer.getCustomerTypeId());
				if(dict != null) {
					customer.setCustomerTypeName(dict.getName()==null?dict.getValue():dict.getName());
				}
			}
			if (service.save(customer) > 0) {
				return R.saveOk(customer.getId());
			} else {
				return R.error();
			}
		}catch(Exception e) {
			return R.error();
		}
	}

	@ApiOperation(value="商户更新", notes="更新商户", response=String.class)
	@PostMapping("/update")
	@ResponseBody
	R update(@RequestBody Customer customer) {
		if(customer == null) {
			return R.error(1, "商户不经存在");
		}
		if(checkLinkerPhone(customer.getId(),customer.getLinkerPhone())) {
			return R.error(1, "联系电话已经存在");
		}
		Customer c = service.get(customer.getId());
		if(c == null) {
			return R.error(1, "商户不经存在");
		}
		if(c.getStatus() != null && c.getStatus()>0) {
			customer.setStatus(1L);
		}else {
			if(customer.getCurrentStep()>7) {
				customer.setStatus(1L);
			}else {
				customer.setStatus(0L);
			}
		}
		if(customer.getCustomerTypeId() != null && customer.getCustomerTypeId()>0) {
			SysDictDO dict = sysDictService.get((long)customer.getCustomerTypeId());
			if(dict != null) {
				customer.setCustomerTypeName(dict.getName()==null?dict.getValue():dict.getName());
			}
		}
		if (service.update(customer) > 0) {
			return R.saveOk(customer.getId());
		} else {
			return R.error();
		}
	}

	@ApiOperation(value="商户删除", notes="根据商户id删除", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "商户id", required = true,paramType="query", dataType = "Long")
	})
	@GetMapping("/remove")
	@ResponseBody
	R remove(Long id) {
		if (service.remove(id) > 0) {
			return R.ok();
		} else {
			return R.error();
		}
	}
	
	/**
	 * 检查商户的联系电话是否存在
	 * @param id           商户id
	 * @param linkerPhone  联系电话
	 * @return
	 */
	boolean checkLinkerPhone(Long id, String linkerPhone) {
		
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("id", id);
		param.put("linkerPhone", linkerPhone);
		int result = service.checkLinkerPhone(param);
		return result>0?true:false;
	}
	
	
	@ApiOperation(value="商户登录", notes="根据手机号和验证码登录，返回商户id", response=String.class)
	@ApiImplicitParams({
        @ApiImplicitParam(name = "phone", value = "手机号码", required = true, paramType="query",dataType = "String"),
        @ApiImplicitParam(name = "veriCode", value = "验证码", required = true, paramType="query",dataType = "String")
	})
	@GetMapping("/loginByPhone")
	@ResponseBody
	R loginByPhone(@RequestParam("phone")String phone,@RequestParam("veriCode")String veriCode) {
			R r = new R();
			VeriCode vc = veriCodeService.getByPhone(phone);
			if(vc == null) {
				return R.error("验证码不存在");
			}
			if(!veriCode.equals(vc.getCode())) {
				return R.error("验证码不正确");
			}
			Map<String,Object> codeMap = new HashMap<String,Object>();
			codeMap.put("type", "codePeriod");
			SysDictDO codeDict =  sysDictService.list(codeMap).get(0);
			if((new Date().getTime()-vc.getCreateTime().getTime()) > Integer.parseInt(codeDict.getValue())*60000) {
				return R.error("验证码已经过期，请重新获取验证码");
			}
			veriCodeService.removeByPhone(phone);
			Customer c = service.getByPhone(phone);
			if(c != null) {
				if(c.getStatus() != 2) {
					return R.error("商户还没有审核通过,不能登录");
				}
				r.put("id", c.getId());
				return r;
			}else {
				return R.error("商户不存在");
			}
	}
	
	
	@ApiOperation(value="商户审核", notes="更新商户审核状态", response=String.class)
	@PostMapping("/audit")
	@ResponseBody
	R audit(@RequestBody Audit audit) {
		
		
		Customer customer = service.get((long)audit.getBzId());
		if(customer == null) {
			return R.error(1, "商户不存在");
		}else {
			if(audit.getAuditResult() == 0) {
				customer.setStatus(3L);
			}else {
				customer.setStatus(2L);
				CustomerQrCode code = new CustomerQrCode();
				code.setCustomerId(customer.getId());
				try {
					code.setImgStr(QRCodeUtil.getCustomerQRCode(customer.getId()));
				}catch(Exception e) {
					
				}
				customerQrCodeService.save(code);
			}
		}
		auditService.save(audit);
		if (service.update(customer) > 0) {
			return R.ok();
		} else {
			return R.error();
		}
	}
	
	
}
